package com.qianfeng.smartdevice.utils;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Created by wenka on 2022/3/14 20:47
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class MD5Utils {
    private static String zifu = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";

    private static List chars = new ArrayList();

    static {
        char[] charArray = zifu.toCharArray();
        System.err.println(Arrays.toString(charArray));
        //chars = Arrays.asList(charArray);
        //遍历放到集合中,最终变成一个集合
        for (char c : charArray) {
            //上面集合中就是所有的字符串了
            chars.add(c);
        }
    }

    public static String getRandomString(int size) {
        //  char[] chars = zifu.toCharArray();//转成char数组
        //    System.err.println(chars);
        //打乱集合,相当于我们生活中的洗牌
        Collections.shuffle(chars);
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        //根据我们传递的长度来生成指定长度的随机字符串
        for (int i = 0; i < size; i++) {
            //获取一个范围在数组长度范围内的数字.

            int index = random.nextInt(chars.size());
            stringBuffer.append((chars.get(index)).toString());
        }
        return stringBuffer.toString();
    }


    public static String getMd5(String source, String salt, int times) {
        if (times == 1) {
            return DigestUtils.md5DigestAsHex((salt + source + salt).getBytes(StandardCharsets.UTF_8));
        } else {
            --times;

            return getMd5(getMd5(source, salt, 1), salt, times);
        }
    }
}
